<template>
  <div class="statistics" v-loading="fullscreenLoading">
    <div class="statistics_search">
      <div class="search_box">
        <el-radio-group v-model="timeType">
          <el-radio-button
            v-for="item in timeOptions"
            :key="item.value"
            :label="item.value"
            >{{ item.name }}
          </el-radio-button>
        </el-radio-group>
      </div>
      <div class="search_box">
        <el-date-picker
          v-model="dateTime"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="dateTimeChange"
        >
        </el-date-picker>
      </div>
    </div>
    <div class="statistics_content">
      <div class="left_content">
        <div class="title">终端收入统计</div>
        <div class="detail_box">
          <div class="chart_box">
            <div ref="piechart" style="height: 326px;"></div>
          </div>
        </div>
        <div class="list_box">
          <div class="list_title">
            <span>终端收入统计表格</span>
          </div>
          <page-table-new
            :tableData="tableData"
            :total="total"
            :hasPage="false"
            ref="pageTable"
            :tableColumns="tableColumns || []"
          >
          <!-- 终端类型 -->
          <template #clienttype="scope">
            <div>
              <span v-if="scope.row.clienttype === 0">PC</span>
              <span v-if="scope.row.clienttype === 1">Android</span>
              <span v-if="scope.row.clienttype === 2">IOS</span>
            </div>
          </template>
          </page-table-new>
        </div>
      </div>
      <div>
        <div class="title">
          <span>{{ childRoleName }}</span>收入统计
        </div>
        <div class="detail_box">
          <div class="switch_type">
            <el-switch
              style="display: block;"
              v-model="chartType"
              :height="16"
              :width="32"
              @change="typeChange"
              :disabled="isRender"
              active-color="#1183fb"
              inactive-color="#1183fb"
              active-text="趋势分析"
              inactive-text="数据分析"
            >
            </el-switch>
          </div>
          <div class="chart_box">
            <div ref="lineChart" style="height: 326px;"></div>
          </div>
        </div>
        <div class="list_box">
          <div class="list_title">
            <span>{{ childRoleName }}</span><span>收入统计表格</span>
          </div>
          <page-table-new
            v-if="roleType === '2'"
            :tableData="assistTableDate"
            :total="assistTotal"
            :featchData="assistFeatchData"
            @pageChange="assistHandlePageChange"
            ref="pageTable"
            :tableColumns="assistTableColumns || []"
          >
            <!-- 日期 -->
            <template #day="scope">
              <div>
                {{ dateDayFormat(scope.row.day) }}
              </div>
            </template>
          </page-table-new>
          <page-table-new
            v-else
            :tableData="inComeTableData"
            :total="inComeTotal"
            :featchData="inComeFeatchData"
            @pageChange="handlePageChange"
            ref="pageTable"
            :tableColumns="inComeTableColumns || []"
          >
          </page-table-new>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import pageTableNew from "@com/tableNew";
import {
  TIME_CHOOSE_OPTIONS,
  TERMINAL_COLUMNS_LIST,
  INCOME_TABLE_COLUMNS,
  PROMOTERS_COLUMNS_LIST
} from "./const";
import { clientCount,agencyCount,trendCount,assistDateCount } from "@/api/overview";
import { getCookie } from "@/utils/auth";

import { formatDate } from "@/utils/validate";
export default {
  name: 'statisticsOverview',
  components: { pageTableNew },
  data() {
    return {
      fullscreenLoading:false,
      timeType: "1", //1: 近1个月 2: 近2个月 3：近3个月
      roleType: getCookie("roleType"),
      childRoleName:'',
      dateTime: [],
      tableData: [], //终端收录统计的列表
      assistTableDate:[], //推广员表格数据
      drawData:{},  //推广商表格参数
      drawTrendData:{}, //趋势统计图表
      total: 0,
      inComeTotal: 0,
      assistTotal:0,
      chartType: false,
      isRender: false, //增加循环切换渲染图表
      timeOptions: TIME_CHOOSE_OPTIONS,
      inComeFeatchData: {
        pageSize: 20,
        pageStart: 1,
      },
      assistFeatchData: {
        pageSize: 20,
        pageStart: 1,
      },
      tableColumns: TERMINAL_COLUMNS_LIST,
      inComeTableData: [],
      assistTableColumns: [],
      inComeTableColumns: []
    };
  },
  created() {
    this.childRoleName = this.$store.state.user.childRoleName;
    var nowDate = new Date();
    let y = nowDate.getFullYear();
    let M = nowDate.getMonth();
    let d = nowDate.getDate();
    this.dateTime = [
      formatDate(new Date(new Date(y+'-'+M+'-'+d).getTime() + 86400000),'yyyy-MM-dd'),
      formatDate(new Date(new Date()),'yyyy-MM-dd'),
    ]
    
    this.assistTableColumns = PROMOTERS_COLUMNS_LIST.map((item) => {
      let obj = { ...item};
      if(obj.sortable){
        delete obj.sortable
      }
      return obj;
    })
    this.inComeTableColumns = INCOME_TABLE_COLUMNS.map((item) => {
      let obj = { ...item};
      if(obj.sortable){
        delete obj.sortable
      }
      if(obj.key === 'name'){
        obj.label = this.childRoleName;
      }
      return obj;
    })
  },
  mounted() {
    this.getClientCount();  // 终端收入统计
    this.getTrendCount();   // 趋势分析统计
    if(this.roleType === '2'){
      this.getAssistDateCount() // 推广员统计
    }else{
      this.getAgencyCount();  // 推广商推广员收入统计
    }
  },
  watch:{
    timeType:function(val,old){
      var nowDate = new Date();
      let y = nowDate.getFullYear();
      let M = nowDate.getMonth();
      let d = nowDate.getDate();
      if(val === "2"){
        M = M - 1;
      }else if(val === "3"){
        M = M - 2;
      }
      this.dateTime = [
        formatDate(new Date(new Date(y+'-'+M+'-'+d).getTime() + 86400000),'yyyy-MM-dd'),
        formatDate(new Date(new Date()),'yyyy-MM-dd'),
      ]
      this.chartType = false;
      this.inComeFeatchData.pageStart = 1;
      this.assistFeatchData.pageStart = 1;
      this.getClientCount();
      this.getTrendCount();
      if(this.roleType === '2'){
        this.getAssistDateCount() // 推广员统计
      }else{
        this.getAgencyCount();  // 推广商推广员收入统计
      }
    }
  },
  computed: {
    dateDayFormat(){
      return function(date){
        if(date){
          return formatDate(new Date(date),'MM-dd')
        }
      }
    }
  },
  methods: {
    getClientCount(){
      this.fullscreenLoading = true;
      var data = {
        startAt: this.dateTime[0]?new Date(formatDate(new Date(this.dateTime[0]),'yyyy-MM-dd')+' 00:00:00').getTime():'',
        endAt: this.dateTime[1]?new Date(formatDate(new Date(this.dateTime[1]),'yyyy-MM-dd')+' 23:59:59').getTime():'',
      }
      clientCount(data).then((res)=>{
        this.fullscreenLoading = false;
       if(res.code === 0){
          this.tableData = res.data;
          let data = {};
          res.data.forEach(item => {
            if(item.clienttype === 1){
              data.IOSPaymoney = item.paymoney;
            }else if(item.clienttype === 2){
              data.AndroidPaymoney = item.paymoney;
            }else{
              data.PCPaymoney = item.paymoney;
            }
          });
          this.drawPie(data);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    handlePageChange(data) {
      this.chartType = false;
      this.inComeFeatchData.pageStart = data.pageStart;
      this.getAgencyCount();
    },
    assistHandlePageChange(data){
      this.chartType = false;
      this.assistFeatchData.pageStart = data.pageStart;
      this.getAssistDateCount();
    },
    getAgencyCount(){
      let data = {
        startAt: this.dateTime[0]?new Date(formatDate(new Date(this.dateTime[0]),'yyyy-MM-dd')+' 00:00:00').getTime():'',
        endAt: this.dateTime[1]?new Date(formatDate(new Date(this.dateTime[1]),'yyyy-MM-dd')+' 23:59:59').getTime():'',
        page: this.inComeFeatchData.pageStart,
        pageSize: this.inComeFeatchData.pageSize
      }
      agencyCount(data).then((res)=>{
       if(res.code === 0){
          this.inComeTableData = res.data.values || [];
          this.inComeTotal = res.data.total;
          this.drawData = {
            name:[],
            regnum:[],
            money:[],
          };
          this.inComeTableData.forEach(item => {
            this.drawData.name.push(item.name);
            this.drawData.regnum.push(item.regnum)
            this.drawData.money.push(item.paymoney)
          });
          this.drawDataAnalysis(this.drawData);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    getAssistDateCount(){
      let data = {
        startAt: this.dateTime[0]?new Date(formatDate(new Date(this.dateTime[0]),'yyyy-MM-dd')+' 00:00:00').getTime():'',
        endAt: this.dateTime[1]?new Date(formatDate(new Date(this.dateTime[1]),'yyyy-MM-dd')+' 23:59:59').getTime():'',
        page: this.assistFeatchData.pageStart,
        pageSize: this.assistFeatchData.pageSize
      }
      assistDateCount(data).then((res)=>{
       if(res.code === 0){
          this.assistTableDate = res.data.values;
          this.assistTotal = res.data.total;
          this.drawData = {
            name:[],
            regnum:[],
            money:[],
          };
          res.data.values.forEach(item => {
            this.drawData.name.push(this.dateDayFormat(item.day));
            this.drawData.regnum.push(item.regnum)
            this.drawData.money.push(item.paymoney)
          });
          this.drawDataAnalysis(this.drawData);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    getTrendCount(){
      let data = {
        startAt: this.dateTime[0]?new Date(formatDate(new Date(this.dateTime[0]),'yyyy-MM-dd')+' 00:00:00').getTime():'',
        endAt: this.dateTime[1]?new Date(formatDate(new Date(this.dateTime[1]),'yyyy-MM-dd')+' 23:59:59').getTime():'',
      }
      trendCount(data).then((res)=>{
       if(res.code === 0){
          this.drawTrendData = {
            dateName:[],
            num:[],
            paymoney:[],
          }
          res.data.forEach(item => {
            let date = formatDate(new Date(item.opat),'M-d');
            this.drawTrendData.dateName.push(date);
            this.drawTrendData.num.push(item.num);
            this.drawTrendData.paymoney.push(item.paymoney);
          });
          // this.drawTrendAnalysis(this.drawTrendData);
        }else{
          this.$message.error(res.message);
        }
      })
    },
    dateTimeChange(){
      this.inComeFeatchData.pageStart = 1;
      this.assistFeatchData.pageStart = 1;
      this.timeType = '';
      this.getClientCount();
      this.getTrendCount();
      if(this.roleType === '2'){
        this.getAssistDateCount() // 推广员统计
      }else{
        this.getAgencyCount();  // 推广商推广员收入统计
      }
    },
    drawPie(data) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.piechart);
      // 绘制图表
      myChart.setOption({
        tooltip: {},
        legend: {
          icon: "circle",
          orient: "horizontal",
          left: "right",
          itemHeight: 8,
          textStyle: {
            padding: [2, 0, 0, 0]
          }
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "50%",
            data: [
              {
                value: data.AndroidPaymoney,
                name: "Android",
                itemStyle: {
                  color: "#3AA0FF"
                }
              },
              {
                value: data.PCPaymoney,
                name: "端游",
                itemStyle: {
                  color: "#FACC14"
                }
              },
              {
                value: data.IOSPaymoney,
                name: "IOS",
                itemStyle: {
                  color: "#2FC25B"
                }
              }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    },
    //绘制数据分析
    drawDataAnalysis(data) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.lineChart);
      let myChartColors = ['#13C2C2','#FF7B88'];
      myChart.clear();
      // 绘制图表
      myChart.setOption({
        color: myChartColors,
        tooltip: {
          trigger: "axis",
          position: function(point, params, dom, rect, size) {
            // 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
            var x = point[0]; //
            var y = point[1];
            var boxWidth = size.contentSize[0];
            var boxHeight = size.contentSize[1];
            var posX = 0; // x坐标位置
            var posY = 0; // y坐标位置
            if (x < boxWidth) {
              // 左边放不开
              posX = 5;
            } else {
              // 左边放的下
              posX = x - boxWidth;
            }
            if (y < boxHeight) {
              // 上边放不开
              posY = 5;
            } else {
              // 上边放得下
              posY = y - boxHeight;
            }
            return [posX, posY];
          },
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          data: ["注册人数", "充值收入"],
          icon: "circle",
          orient: "horizontal",
          left: "right",
          itemHeight: 10,
          textStyle: {
            padding: [3, 0, 0, 0]
          }
        },
        grid: {
          left: "0",
          right: "2%",
          bottom: "4%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: data.name
        },
        yAxis: [
          {
            type: "value",
            position: 'left',
            splitLine:false,
            axisLine: {
                show: true,
                lineStyle: {
                    color: myChartColors[0]
                }
            }
          },
          {
            type: "value",
            position: 'right',
            axisLine: {
                show: true,
                lineStyle: {
                    color: myChartColors[1]
                }
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: myChartColors[1]
              }
            }
          },
        ],
        series: [
          {
            name: "注册人数",
            type: "bar",
            barGap: 0,
            data: data.regnum,
            itemStyle: {
              color: myChartColors[0]
            }
          },
          {
            name: "充值收入",
            barGap: 0,
            type: "bar",
            data: data.money,
            yAxisIndex: 1,
            itemStyle: {
              color: myChartColors[1]
            }
          }
        ]
      });
    },
    //绘制趋势分析
    drawTrendAnalysis(data) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(this.$refs.lineChart);
      let myChartColors = ['#13C2C2','#FF7B88'];
      myChart.clear();
      myChart.setOption({
        title: {
          text: ""
        },
        tooltip: {
          trigger: "axis",
          position: function(point, params, dom, rect, size) {
            // 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
            var x = point[0]; //
            var y = point[1];
            var boxWidth = size.contentSize[0];
            var boxHeight = size.contentSize[1];
            var posX = 0; // x坐标位置
            var posY = 0; // y坐标位置
            if (x < boxWidth) {
              // 左边放不开
              posX = 5;
            } else {
              // 左边放的下
              posX = x - boxWidth;
            }
            if (y < boxHeight) {
              // 上边放不开
              posY = 5;
            } else {
              // 上边放得下
              posY = y - boxHeight;
            }
            return [posX, posY];
          }
        },
        legend: {
          data: ["注册人数", "充值收入"],
          icon: "circle",
          orient: "horizontal",
          left: "right",
          itemHeight: 8,
          textStyle: {
            padding: [2, 0, 0, 0]
          }
        },
        grid: {
          left: "0%",
          right: "2%",
          bottom: "4%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.dateName
        },
        yAxis: [
          {
            type: "value",
            position: 'left',
            splitLine:false,
            axisLine: {
                show: true,
                lineStyle: {
                    color: myChartColors[0]
                }
            }
          },
          {
            type: "value",
            position: 'right',
            axisLine: {
                show: true,
                lineStyle: {
                    color: myChartColors[1]
                }
            },
            splitLine: {
              show: false,
              lineStyle: {
                type: "dashed",
                color: myChartColors[1]
              }
            }
          },
        ],
        series: [
          {
            name: "注册人数",
            type: "line",
            data: data.num,
            itemStyle: {
              color: myChartColors[0]
            }
          },
          {
            name: "充值收入",
            type: "line",
            data: data.paymoney,
            yAxisIndex: 1,
            itemStyle: {
              color: myChartColors[1]
            }
          }
        ]
      });
    },
    typeChange(val) {
      this.isRender = true;
      if (val) {
        this.drawTrendAnalysis(this.drawTrendData);
      } else {
        this.drawDataAnalysis(this.drawData);
      }
      setTimeout(() => {
        this.isRender = false;
      }, 1000);
    }
  }
};
</script>
<style lang="scss">
.statistics {
  .switch_type {
    .el-switch__core {
      height: 16px;
      line-height: 16px;
    }
    .el-switch__core::after {
      height: 12px;
      width: 12px;
    }
    .is-checked .el-switch__core::after {
      margin-left: -13px;
    }
  }
}
</style>
<style lang="scss" scoped>
.statistics {
  .statistics_search {
    height: 36px;
    .search_box {
      display: inline-block;
      vertical-align: top;
      margin-right: 6px;
    }
  }
  margin-bottom: 20px;
  .statistics_content {
    margin-top: 16px;
    display: flex;
    & > div {
      background: #fff;
      box-shadow: 0 0 6px 0 rgba(0, 21, 41, 0.09);
      border-radius: 4px;
      flex: 1;
      min-height: 100px;
      .title {
        box-sizing: border-box;
        height: 45px;
        line-height: 44px;
        border-bottom: 1px solid #e2e5ee;
        padding: 0px 16px;
        font-family: PingFangSC-Semibold;
        font-size: 16px;
        color: #404040;
        font-weight: 700;
      }
      .detail_box {
        padding: 0px 16px;
        margin-top: 16px;
        position: relative;
        .chart_box {
          border-bottom: 1px solid #e2e5ee;
        }
        .switch_type {
          position: absolute;
          left: 16px;
          top: 3px;
          z-index: 999;
        }
      }
      .list_box {
        margin-top: 16px;
        padding: 0px 16px 16px 16px;
        padding-bottom: 0;
        .list_title {
          margin-bottom: 10px;
          span {
            font-family: PingFangSC-Semibold;
            font-size: 14px;
            color: #404040;
            line-height: 24px;
            font-weight: 600;
            display: inline-block;
          }
        }
      }
    }
    .left_content {
      margin-right: 16px;
      height: 600px;
    }
  }
}
</style>
